<template>
  <view class="container">
    <!-- 文章详情 -->
    <view class="article-detail">
      <!-- 加载状态 -->
      <view class="loading" v-if="loading">
        <view class="loading-content">
          <text class="loading-text">加载中...</text>
        </view>
      </view>
      
      <!-- 文章内容 -->
      <block v-else-if="article">
        <!-- 标题 -->
        <view class="article-header">
          <text class="article-title">{{ article.title }}</text>
          <view class="article-meta">
            <text class="author">{{ article.author || '未知作者' }}</text>
            <text class="publish-time">{{ formatDate(article.publishTime) }}</text>
            <text class="view-count">{{ formatReadCount(article.viewCount) }}阅读</text>
          </view>
        </view>
        
        <!-- 封面图 -->
        <image 
          v-if="article.coverImage" 
          :src="processImageUrl(article.coverImage)" 
          class="article-cover" 
          mode="widthFix"
          @error="handleImageError"
        ></image>
        
        <!-- 正文内容 -->
        <view class="article-content">
          <rich-text :nodes="formatContent(article.content)"></rich-text>
        </view>
        
        <!-- 标签 -->
        <view class="article-tags" v-if="article.tags && article.tags.length > 0">
          <text class="tag-title">标签：</text>
          <view class="tags-list">
            <text 
              v-for="(tag, index) in article.tags" 
              :key="index" 
              class="tag"
            >{{ tag }}</text>
          </view>
        </view>
      </block>
      
      <!-- 错误状态 -->
      <view class="error" v-else>
        <text class="error-text">{{ errorMsg || '加载文章失败' }}</text>
        <!-- 修复事件绑定，使用 @tap 兼容小程序 -->
        <button class="retry-btn" @tap="getArticleDetail">重试</button>
      </view>
    </view>
  </view>
</template>

<script>
import articleApi from '@/api/article';
import mixin from '../../utils/mixin';

export default {
  mixins: [mixin],
  data() {
    return {
      article: null,
      loading: true,
      errorMsg: '',
      defaultCover: 'http://localhost:9001/image/article/67fce526-83ba-49ef-9d14-86ab9a803a2b.png',
      loadingText: {
        contentdown: '上拉显示更多',
        contentrefresh: '加载中...',
        contentnomore: '没有更多数据了'
      },
      articleId: null
    };
  },
  methods: {
    formatReadCount(count) {
      if (!count) return '0';
      count = Number(count);
      if (count >= 1000) {
        return (count / 1000).toFixed(1) + 'k';
      }
      return count.toString();
    },
    formatDate(dateStr) {
      if (!dateStr) return '未知时间';
      // 兼容iOS
      const safeStr = dateStr.replace(/-/g, '/');
      const date = new Date(safeStr);
      if (isNaN(date.getTime())) return '未知时间';
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    formatContent(content) {
      if (!content) return '';
      return content;
    },
    handleImageError() {
      if (this.article) {
        this.article.coverImage = this.defaultCover;
      }
    },
    async getArticleDetail() {
      if (!this.articleId) {
        this.errorMsg = '文章ID不存在';
        this.loading = false;
        return;
      }
      this.loading = true;
      this.errorMsg = '';
      try {
        const res = await articleApi.getArticleDetail(this.articleId);
        if (res && res.code === 1 && res.data) {
          const data = res.data;
          this.article = {
            ...data,
            coverImage: data.coverImage || data.cover_image || '',
            title: data.title || data.articleTitle,
            publishTime: data.publishTime || data.publish_time || data.createTime || data.updatedAt,
            viewCount: data.viewCount || data.readCount || data.views || 0,
            tags: data.tags || data.tagList || []
          };
          if (this.article.coverImage && !/^https?:\/\//.test(this.article.coverImage)) {
            if (!this.article.coverImage.startsWith('/image')) {
              this.article.coverImage = '/image' + this.article.coverImage.replace(/^\/static/, '');
            }
            // 添加完整的服务器地址
            this.article.coverImage = 'http://localhost:9001' + this.article.coverImage;
          }
          uni.setNavigationBarTitle({
            title: this.article.title || '文章详情'
          });
        } else {
          this.errorMsg = res?.msg || '获取文章详情失败';
        }
      } catch (error) {
        this.errorMsg = '网络错误，请稍后重试';
      } finally {
        this.loading = false;
      }
    }
  },
  onLoad(options) {
    this.articleId = options.id || '';
    this.getArticleDetail();
  }
};
</script>

<style>
.container {
  padding: 30rpx;
  background-color: #fff;
  min-height: 100vh;
}
.loading,
.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-text {
  color: #999;
  font-size: 26rpx;
}
.error-text {
  color: #ff5a5f;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}
.retry-btn {
  font-size: 28rpx;
  padding: 10rpx 30rpx;
  background-color: #2979ff;
  color: #fff;
  border-radius: 8rpx;
}
.article-header {
  margin-bottom: 40rpx;
}
.article-title {
  font-size: 40rpx;
  font-weight: bold;
  line-height: 1.4;
  color: #333;
  margin-bottom: 20rpx;
}
.article-meta {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}
.author {
  margin-right: 20rpx;
}
.publish-time {
  margin-right: 20rpx;
}
.view-count {
  color: #999;
}
.article-cover {
  width: 100%;
  border-radius: 12rpx;
  margin-bottom: 40rpx;
}
.article-content {
  font-size: 30rpx;
  line-height: 1.8;
  color: #333;
  margin-bottom: 60rpx;
}
.article-tags {
  margin-top: 40rpx;
  padding-top: 20rpx;
  border-top: 1px solid #f0f0f0;
}
.tag-title {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 16rpx;
}
.tags-list {
  display: flex;
  flex-wrap: wrap;
}
.tag {
  display: inline-block;
  padding: 6rpx 20rpx;
  background-color: #f5f5f5;
  color: #666;
  font-size: 24rpx;
  border-radius: 100rpx;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
}
</style> 